import request from '@/services/http'

/**
 * 单个文件上传
 * @param file 文件对象
 * @returns Promise<string>
 */
export const uploadFile = async (file: File): Promise<string> => {
  const formData = new FormData()
  formData.append('file', file)

  const response = await request({
    url: '/euc/api/chat/files/upload',
    method: 'POST',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })

  return response.data
}

/**
 * 多文件上传
 * @param files 文件数组
 * @returns Promise<string[]>
 */
export const uploadFiles = async (files: File[]): Promise<string[]> => {
  const formData = new FormData()
  files.forEach((file) => {
    formData.append(`files`, file)
  })

  const response = await request({
    url: '/common/uploadFiles',
    method: 'POST',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })

  return response.data
}

/**
 * 通用文件上传方法
 * @param files 文件或文件数组
 * @returns Promise<string | string[]>
 */
export const upload = async (files: File | File[]): Promise<string | string[]> => {
  if (Array.isArray(files)) {
    if (files.length === 0) {
      throw new Error('文件列表不能为空')
    }

    if (files.length === 1) {
      return await uploadFile(files[0])
    } else {
      return await uploadFiles(files)
    }
  } else {
    return await uploadFile(files)
  }
}
